<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- clearable 文本清空按钮 @clear 清除时事件触发 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <!-- stripe 斑马纹效果  border 添加边框 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话号码"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="状态">
          <!-- 采用template slot-scope 的方式获取对象 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatusChanged(scope.row)"
            >
              <!-- 使用 change 方法监听状态的改变  传入对象 -->
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="small"
              @click="Edit(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色 按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-custom"
                circle
                size="small"
                @click="setUser(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 弹出 添加用户框 信息 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addFormClose"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRuleRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加 编辑用户 信息 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editFormClose"
    >
      <el-form
        :model="editForm"
        :rules="editrules"
        ref="editFormref"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 卡片 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setdialogVisible"
      width="50%"
      @close="closeSetdialog"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRole" placeholder="请选择">
            <el-option
              v-for="item in roleListInfo"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserInfo(userInfo.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义 验证规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) return cb()
      // 否则不合法
      cb(new Error('邮箱不合法'))
    }
    // 电话号码 验证规则
    var checkPhoneNumber = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regPhoneNumber = /^1[3|4|5|7|8][0-9]{9}$/
      if (regPhoneNumber.test(value)) return cb()
      // 否则不合法
      cb(new Error('手机号码不合法'))
    }
    return {
      userList: [],
      // 请求数据对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      // 添加用户初始状态
      addDialogVisible: false,
      // 编辑用户初始状态
      editdialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkPhoneNumber,
            trigger: 'blur',
          },
        ],
      },
      // 编辑
      editForm: {
        username: '',
        email: '',
        mobile: '',
      },
      editrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkPhoneNumber,
            trigger: 'blur',
          },
        ],
      },
      // 分配角色 初始状态
      setdialogVisible: false,
      // 储存 分配角色 信息
      userInfo: {},
      roleListInfo: {},
      // 选中的角色
      selectRole: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    closeSetdialog() {},
    async getUserList() {
      // 请求用户列表
      const { data } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(data)
      if (data.meta.status !== 200) return this.$message.error('获取失败')
      // 存储数据
      this.userList = data.data.users
      this.total = data.data.total
    },
    // 获取页面长度
    handleSizeChange(newSizeList) {
      this.queryInfo.pagesize = newSizeList
      // 重新请求数据
      this.getUserList()
    },
    // 获取页码
    handleCurrentChange(newPages) {
      this.queryInfo.pagenum = newPages
      this.getUserList()
    },
    // 切换状态方法
    async userStatusChanged(userStatusInfo) {
      // console.log(userStatusInfo)
      const { data } = await this.$http.put(
        // 根据携带的参数 发送put请求
        `users/${userStatusInfo.id}/state/${userStatusInfo.mg_state}`
      )
      console.log(data)
      if (data.meta.status !== 200) {
        userStatusInfo.mg_state = !userStatusInfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 监听 添加用户事件的关闭
    addFormClose() {
      // 找到ref的事件源  使用resetFields()方法 进行重置
      this.$refs.addRuleRef.resetFields()
    },
    // 添加 用户 请求``
    addUser() {
      this.$refs.addRuleRef.validate(async (valid) => {
        if (!valid) return false
        // 发起真实的 添加用户 请求
        const { data } = await this.$http.post('users', this.addForm)
        // console.log(data)
        if (data.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        // 隐藏 用户添加 框
        this.addDialogVisible = false
        // 重新加载数据
        this.getUserList()
      })
    },
    // 点击编辑按钮 事件
    async Edit(id) {
      const { data } = await this.$http.get('users/' + id)
      if (data.meta.status !== 200) return this.$message.error('查询失败')
      this.$message.success('查询成功')
      this.editForm = data.data
      this.editdialogVisible = true
    },
    // 编辑用户 请求
    editUser() {
      // 先预校验
      this.$refs.editFormref.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        const { data } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        })
        if (data.meta.status !== 200) return this.$message.error('更新信息失败')
        // 更新数据
        this.getUserList()
        this.editdialogVisible = false
        this.$message.success('更新用户信息成功')
      })
    },
    // 监听 编辑菜单 关闭事件
    editFormClose() {
      // 重置状态
      this.$refs.editFormref.resetFields()
    },
    // 监听 删除 按钮 事件
    removeUserById(id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          // 进行删除操作
          this.$http.delete('users/' + id)
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 分配角色 按钮
    async setUser(userInfo) {
      this.userInfo = userInfo
      // 获取下拉框角色列表
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleListInfo = data.data
      this.setdialogVisible = true
    },
    // 点击分配角色 确定 修改按钮事件
    async setUserInfo(id) {
      if (!this.selectRole) return this.$message.error('请选择分配角色')
      const { data } = await this.$http.put(`users/${id}/role`, {
        rid: this.selectRole,
      })
      if (data.meta.status !== 200) return this.$message.error('分配角色失败')
      this.getUserList()
      this.$message.success('分配角色成功')
      this.setdialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
</style>
